package com.application.model;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RetrievePais extends RetrivierWeb {

	
	
    public RetrievePais() {    	
    }

    @Override
    public void processContent(String data,String parentName) {
        String option="";
//        ((LinkedList<String>)desendencia).add(parentName);
        option=getOption(data);
        if(option.equalsIgnoreCase("Regiones")){
            processRegiones(data,parentName);            
        }else if(option.equalsIgnoreCase("Barrios")){
            processBarrios(data,parentName);
        }else if(option.equalsIgnoreCase("Partidos")){
            processPartidos(data,parentName);
        }else if(option.equalsIgnoreCase("Localidades")){
            processLocalidades(data,parentName);
        }else if(option.equalsIgnoreCase("")){
        }else if(option.equalsIgnoreCase("")){
        }else{
            
        }
        

    }

    private void getRegionesByPais(String paisId, String parentName) {
        super.retrivie("http://www.argenprop.com/Regiones/FindRegionesByPaisBusqueda?idPais=" + paisId,parentName, null, null,"utf-8");
    }

    public void retrieve() {
        String pais = "";
        String paisId = "";
        String paisDato = "<select id=sp.Pais name=sp.Pais><option selected=selected value=1>Argentina</option>";
        paisDato += "<option value=3>Uruguay</option>";
        paisDato += "<option value=4>Bolivia</option>";
        paisDato += "<option value=5>Brasil</option>";
        paisDato += "<option value=6>Chile</option>";
        paisDato += "<option value=7>Paraguay</option>";
        paisDato += "<option value=8>Otros países</option>";
        paisDato += "</select>";

        String regex = "value=([0123456789]{1,})>(.*?)</option>";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNICODE_CASE | Pattern.UNIX_LINES);
        Matcher matcher = pattern.matcher(paisDato);
        while (matcher.find()) {
            paisId = matcher.group(1);
            pais = matcher.group(2);
            logger.info("INSERT INTO pais(name) values('"+unescapeHtml(pais)+"');");
            getRegionesByPais(paisId,pais);
        }
    }

    private String getOption(String data) {
        String value="";
        String regex = "\\{\"(.*?)\":(.*)";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNICODE_CASE | Pattern.UNIX_LINES);
        Matcher matcher = pattern.matcher(data);
        if (matcher.find()) {
            value=matcher.group(1);
        }
        return value;
    }

    private void processRegiones(String data, String parentName) {
        String nombre = "";
        String id = "";
        String enabled = "";
        Pattern pattern = null;
        Matcher matcher = null;
        pattern = Pattern.compile("\"Nombre\":\"(.*?)\",\"Id\":(.*?),\"ShowMatchedRegions\":(.*?)}", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        matcher = pattern.matcher(data);
        while (matcher.find()) {
            nombre = matcher.group(1);
            id = matcher.group(2);
            enabled = matcher.group(3);
            logger.info("INSERT INTO provincia(pais_id,name) values((select id from pais where name='"+unescapeHtml(parentName)+"'),'" + unescapeHtml(nombre)+"');");
            
            super.retrivie("http://www.argenprop.com/Regiones/FindChildrenByRegionBusqueda?idRegionBusqueda=" + id,nombre, null, null,"utf-8");
        }
    }

    private void processBarrios(String data, String parentName) {
        String nombre = "";
        String barrio = "";
        String id = "";
        String enabled = "";
        String abueloName = "";
        Pattern pattern = null;
        Matcher matcher = null;
        Pattern patternSub = null;
        Matcher matcherSub = null;
        pattern = Pattern.compile("\\{\"Nombre\":\"(.*?)\",\"Id\":(.*?),(.*?)\"SubBarrios\":\\[(.*?)\\]", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        matcher = pattern.matcher(data);
//        abueloName = ((LinkedList<String>)desendencia).removeLast();
        abueloName = ((LinkedList<String>)desendencia).removeLast();
        logger.info("INSERT INTO partido(provincia_id,name) VALUES((SELECT id FROM provincia WHERE name='"+unescapeHtml(parentName)+"'),'" +unescapeHtml(parentName)+"');");
        while (matcher.find()) {
        	barrio = matcher.group(1);
            id = matcher.group(2);
            enabled = matcher.group(4);
//                        iteracion=2;
            
            logger.info("INSERT INTO localidad(partido_id,name) VALUES((SELECT id FROM partido WHERE name='"+unescapeHtml(parentName)+"' AND provincia_id=(SELECT id FROM provincia WHERE name='"+unescapeHtml(parentName)+"')),'" + unescapeHtml(barrio)+"');");

            patternSub = Pattern.compile("\\{\"Nombre\":\"(.*?)\",\"Id\":(.*?)\\}", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            matcherSub = patternSub.matcher(enabled);
            while (matcherSub.find()) {
                nombre = matcherSub.group(1);
                id = matcherSub.group(2);
                logger.info("INSERT INTO barrio(localidad_id,name) VALUES((SELECT id FROM localidad WHERE name='"+unescapeHtml(barrio)+"' AND partido_id=(SELECT id FROM partido WHERE name='"+unescapeHtml(parentName)+"' AND provincia_id=(SELECT id FROM provincia WHERE name='"+unescapeHtml(parentName)+"'))),'" + unescapeHtml(nombre)+"');");
            }
        }
        
    }

    private void processPartidos(String data, String parentName) {
        String nombre = "";
        String id = "";
        Pattern pattern = null;
        Matcher matcher = null;
        pattern = Pattern.compile("\\{\"Nombre\":\"(.*?)\",\"Id\":([0123456789]{1,})(.*?)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        matcher = pattern.matcher(data);
        while (matcher.find()) {
            nombre=matcher.group(1);
            id=matcher.group(2);
            logger.info("INSERT INTO partido(provincia_id,name) VALUES((SELECT id FROM provincia where name='"+unescapeHtml(parentName)+"'),'" + unescapeHtml(nombre)+"');");
            retrivie("http://www.argenprop.com/Regiones/FindLocalidadesDto?idPartido=" + id,nombre, null, null,"utf-8");
        }
    }

    private void processLocalidades(String data, String parentName) {
        String nombre = "";
        String localidad = "";
        String id = "";
        String enabled = "";
        String abueloName = "";
        
        Pattern pattern = null;
        Matcher matcher = null;
        Pattern patternSub = null;
        Matcher matcherSub = null;
        pattern = Pattern.compile("\\{\"Nombre\":\"(.*?)\",\"Id\":([0123456789]{1,}),(.*?)\\\"Barrios\\\":\\[(.*?)\\]", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        matcher = pattern.matcher(data);
        abueloName = ((LinkedList<String>)desendencia).removeLast();
        abueloName = ((LinkedList<String>)desendencia).removeLast();

        while (matcher.find()) {
        	localidad = matcher.group(1);
            id = matcher.group(2);
            enabled = matcher.group(4);
//                        iteracion=2;
            logger.info("INSERT INTO localidad(partido_id,name) VALUES((SELECT id FROM partido WHERE name='"+unescapeHtml(parentName)+"' AND provincia_id=(SELECT id FROM provincia WHERE name='"+unescapeHtml(abueloName)+"')),'" + unescapeHtml(localidad)+"');");

            patternSub = Pattern.compile("\\{\"Nombre\":\"(.*?)\",\"Id\":([0123456789]{1,})\\}", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            matcherSub = patternSub.matcher(enabled);
            while (matcherSub.find()) {
                nombre = matcherSub.group(1);
                id = matcherSub.group(2);
                logger.info("INSERT INTO barrio(localidad_id,name) VALUES((SELECT id FROM localidad WHERE name='"+unescapeHtml(localidad)+"'AND partido_id=(SELECT id FROM partido WHERE name='"+unescapeHtml(parentName)+"' AND provincia_id=(SELECT id FROM provincia WHERE name='"+unescapeHtml(abueloName)+"'))),'" + unescapeHtml(nombre)+"');");
            }
        }        
        desendencia.add(abueloName);
    }
}
